﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Maps.MapControl.WPF;

namespace SensorMayhem.Helpers
{
    public static class GeoCodeCalc
    {
        public const double EarthRadiusInMiles = 3956.0;
        public const double EarthRadiusInKilometers = 6367.0;
        public static double ToRadian(double degrees)
        {
            return degrees * (Math.PI / 180);
        }
        public static double ToDegrees(double radians)
        {
            return radians * (180 / Math.PI);
        }

        public static LocationCollection CreateCircle(Location center, double radius, bool inKilometers = true, double jump = 4)
        {
            var earthRadius = inKilometers ? GeoCodeCalc.EarthRadiusInKilometers : GeoCodeCalc.EarthRadiusInMiles;
            var lat = ToRadian(center.Latitude); //radians            
            var lng = ToRadian(center.Longitude); //radians            
            var d = radius / earthRadius; // d = angular distance covered on earth's surface            
            var locations = new LocationCollection();
            for (double x = 0; x <= 360; x += jump)
            {
                var brng = ToRadian(x);
                var latRadians = Math.Asin(Math.Sin(lat) * Math.Cos(d) + Math.Cos(lat) * Math.Sin(d) * Math.Cos(brng));
                var lngRadians = lng + Math.Atan2(Math.Sin(brng) * Math.Sin(d) * Math.Cos(lat), Math.Cos(d) - Math.Sin(lat) * Math.Sin(latRadians));

                var latitude = ToDegrees(latRadians);
                var longitude = ToDegrees(lngRadians);
               
                if (longitude < -180 || longitude > 180 || latitude < -90 || latitude > 90)
                {
                    if (jump == 4)
                    {
                        return new LocationCollection() { center };
                    }
                    continue;
                }
                locations.Add(new Location() { Latitude = latitude, Longitude = longitude });
            }
            return locations;
        }

    }
}
